<template>
    <div class="proportion-config">
        <el-card>
            <div slot="header" class="clearfix">
                <span class="page-title"><i class="el-icon-s-finance"></i> 分佣比例配置</span>
                <div style="float: right;">
                    <el-button style="padding: 3px 0" type="text" @click="refreshAllData">刷新数据</el-button>
                </div>
            </div>

            <!-- 分润比例列表 -->
            <div class="config-section">
                <h3 class="section-title">
                    <i class="el-icon-view"></i>
                    分润比例列表
                </h3>
                <p class="section-desc">所有用户分润比例配置信息，支持单独配置用户的分润比例</p>

                <!-- 查询条件 -->
                <div class="query-form">
                    <el-form :inline="true" :model="queryParams" size="small">
                        <el-form-item label="搜索关键词">
                            <el-input v-model="queryParams.keyword" placeholder="姓名/业务员编号/手机号" clearable
                                style="width: 220px" @keyup.enter.native="handleQuery">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="用户类型">
                            <el-select v-model="queryParams.userType" placeholder="全部" clearable style="width: 150px">
                                <el-option label="C端用户" :value="1"></el-option>
                                <el-option label="业务员" :value="2"></el-option>
                                <el-option label="商家" :value="3"></el-option>
                                <el-option label="区域代理" :value="4"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="配置类型">
                            <el-select v-model="queryParams.useCustomConfig" placeholder="全部" clearable
                                style="width: 150px">
                                <el-option label="默认配置" :value="false"></el-option>
                                <el-option label="自定义配置" :value="true"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <configurable-table :columns="tableColumns" :data="proportionList" :loading="loading"
                    :show-pagination="true" :current-page.sync="queryParams.pageIndex"
                    :page-size.sync="queryParams.pageSize" :pagination-total="total" index-label="序号" index-width="80"
                    @page-change="handlePageChange" border stripe>
                    <!-- 用户类型列 -->
                    <template #userTypeName="{ row }">
                        <el-tag :type="getUserTypeTag(row.userType)" size="small">
                            {{ row.userTypeName || '-' }}
                        </el-tag>
                    </template>

                    <!-- 用户名称列 -->
                    <template #userName="{ row }">
                        <span>{{ row.userName || '-' }}</span>
                    </template>

                    <!-- 手机号码列 -->
                    <template #phone="{ row }">
                        <span>{{ row.phone || '-' }}</span>
                    </template>

                    <!-- 异业联盟分润比例列 -->
                    <template #interIndustryRate="{ row }">
                        <span class="proportion-display">{{ row.interIndustryRate }}%</span>
                    </template>

                    <!-- 广告分润比例列 -->
                    <template #adRate="{ row }">
                        <span class="proportion-display">{{ row.adRate }}%</span>
                    </template>

                    <!-- 绑定的业务员列 -->
                    <template #lockedSalesmanName="{ row }">
                        {{ row.lockedSalesmanName || '-' }}
                    </template>

                    <!-- 业务员编号列 -->
                    <template #lockedSalesmanNo="{ row }">
                        {{ row.lockedSalesmanNo || '-' }}
                    </template>

                    <!-- 操作列 -->
                    <template #actions="{ row }">
                        <el-button size="mini" type="primary" @click="editUserProfitFunc(row)">编辑</el-button>
                    </template>
                </configurable-table>
            </div>

            <!-- 分佣比例概览 -->
            <div class="config-section commission-overview-section">
                <h3 class="section-title">
                    <i class="el-icon-s-shop"></i>
                    分佣比例概览
                </h3>
                <p class="section-desc">各角色在不同业务场景下的分佣占比</p>

                <!-- 分佣比例概览容器 - 横向排列 -->
                <div class="commission-overview-container">
                    <!-- 广告分佣概览 -->
                    <div class="commission-overview-item">
                        <h4 class="overview-item-title">
                            <span>
                                <i class="el-icon-video-camera"></i>
                                广告分佣比例
                            </span>
                        </h4>
                        <p class="overview-item-desc">各角色在广告分佣中的分成占比</p>

                        <!-- 卡片式分佣比例展示 -->
                        <div class="proportion-cards">
                            <div class="proportion-card" v-for="item in getAdProportionItems()" :key="item.key">
                                <div class="card-icon" :style="{ background: item.color }">
                                    <i :class="item.icon"></i>
                                </div>
                                <div class="card-content">
                                    <div class="card-label">{{ item.label }}</div>
                                    <div class="card-value">{{ item.value }}%</div>
                                </div>
                                <div class="card-progress">
                                    <div class="progress-bar"
                                        :style="{ width: item.value + '%', background: item.color }"></div>
                                </div>
                            </div>
                            <div class="proportion-card total-card">
                                <div class="card-icon"
                                    :class="{ 'icon-success': getAdTotal() === 100, 'icon-warning': getAdTotal() !== 100 }">
                                    <i class="el-icon-check" v-if="getAdTotal() === 100"></i>
                                    <i class="el-icon-warning" v-else></i>
                                </div>
                                <div class="card-content">
                                    <div class="card-label">合计</div>
                                    <div class="card-value"
                                        :class="{ 'text-success': getAdTotal() === 100, 'text-danger': getAdTotal() !== 100 }">
                                        {{ getAdTotal().toFixed(2) }}%
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 商家本店消费分佣概览 -->
                    <div class="commission-overview-item">
                        <h4 class="overview-item-title">
                            <span>
                                <i class="el-icon-shopping-bag-2"></i>
                                商家本店消费分佣比例
                            </span>
                        </h4>
                        <p class="overview-item-desc">各角色在商家本店消费分佣中的分成占比</p>

                        <!-- 卡片式分佣比例展示 -->
                        <div class="proportion-cards">
                            <div class="proportion-card" v-for="item in getMerchantStoreProportionItems()"
                                :key="item.key">
                                <div class="card-icon" :style="{ background: item.color }">
                                    <i :class="item.icon"></i>
                                </div>
                                <div class="card-content">
                                    <div class="card-label">{{ item.label }}</div>
                                    <div class="card-value">{{ item.value }}%</div>
                                    <div class="card-subtitle" v-if="item.subtitle">{{ item.subtitle }}</div>
                                </div>
                                <div class="card-progress">
                                    <div class="progress-bar"
                                        :style="{ width: item.value + '%', background: item.color }"></div>
                                </div>
                            </div>
                            <div class="proportion-card total-card">
                                <div class="card-icon"
                                    :class="{ 'icon-success': getMerchantStoreTotal() === 100, 'icon-warning': getMerchantStoreTotal() !== 100 }">
                                    <i class="el-icon-check" v-if="getMerchantStoreTotal() === 100"></i>
                                    <i class="el-icon-warning" v-else></i>
                                </div>
                                <div class="card-content">
                                    <div class="card-label">合计</div>
                                    <div class="card-value"
                                        :class="{ 'text-success': getMerchantStoreTotal() === 100, 'text-danger': getMerchantStoreTotal() !== 100 }">
                                        {{ getMerchantStoreTotal().toFixed(2) }}%
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 异业联盟分佣概览 -->
                    <div class="commission-overview-item">
                        <h4 class="overview-item-title">
                            <span>
                                <i class="el-icon-connection"></i>
                                异业联盟分佣比例
                            </span>
                        </h4>
                        <p class="overview-item-desc">各角色在异业联盟分佣中的分成占比</p>

                        <!-- 卡片式分佣比例展示 -->
                        <div class="proportion-cards">
                            <div class="proportion-card" v-for="item in getAllianceProportionItems()" :key="item.key">
                                <div class="card-icon" :style="{ background: item.color }">
                                    <i :class="item.icon"></i>
                                </div>
                                <div class="card-content">
                                    <div class="card-label">{{ item.label }}</div>
                                    <div class="card-value">{{ item.value }}%</div>
                                </div>
                                <div class="card-progress">
                                    <div class="progress-bar"
                                        :style="{ width: item.value + '%', background: item.color }"></div>
                                </div>
                            </div>
                            <div class="proportion-card total-card">
                                <div class="card-icon"
                                    :class="{ 'icon-success': getAllianceTotal() === 100, 'icon-warning': getAllianceTotal() !== 100 }">
                                    <i class="el-icon-check" v-if="getAllianceTotal() === 100"></i>
                                    <i class="el-icon-warning" v-else></i>
                                </div>
                                <div class="card-content">
                                    <div class="card-label">合计</div>
                                    <div class="card-value"
                                        :class="{ 'text-success': getAllianceTotal() === 100, 'text-danger': getAllianceTotal() !== 100 }">
                                        {{ getAllianceTotal().toFixed(2) }}%
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分佣配置模块 -->
            <div class="config-section commission-config-section">
                <h3 class="section-title">
                    <i class="el-icon-setting"></i>
                    默认分佣比例配置
                </h3>
                <p class="section-desc">配置各角色在不同业务场景下的默认分佣比例，比例总和必须为100%</p>

                <div class="verify-section">
                    <el-alert title="变更默认分佣配置需短信验证" type="warning" description="点击获取验证码发送至当前账号绑定手机号，输入收到的6位验证码后方可保存。"
                        show-icon :closable="false">
                    </el-alert>
                    <div class="verify-form">
                        <el-input v-model="verifyCode" placeholder="请输入短信验证码" maxlength="6" clearable
                            class="verify-input">
                            <template slot="append">
                                <el-button type="primary" @click="handleSendVerifyCode"
                                    :disabled="!userPhone || smsCountdown > 0 || smsSending" :loading="smsSending">
                                    {{ smsCountdown > 0 ? `${smsCountdown}s` : '获取验证码' }}
                                </el-button>
                            </template>
                        </el-input>
                        <div class="verify-help" v-if="userPhone">
                            验证码将发送至 {{ maskPhone(userPhone) }}，若未收到可稍后重试。
                        </div>
                        <div class="verify-help danger" v-else>
                            账号未绑定手机号，无法接收验证码，请先完善个人信息。
                        </div>
                    </div>
                </div>

                <!-- 分佣配置容器 - 横向排列 -->
                <div class="commission-config-container">
                    <!-- 广告分佣配置 -->
                    <div class="commission-config-item">
                        <h4 class="config-item-title">
                            <span>
                                <i class="el-icon-video-camera"></i>
                                广告分佣配置
                            </span>
                            <el-button type="primary" size="small" @click="saveAdConfig"
                                :loading="adLoading">保存配置</el-button>
                        </h4>
                        <p class="config-item-desc">配置各角色在广告分佣中的分成比例，比例范围为 [0, 100)</p>

                        <!-- 可视化分佣比例展示 -->
                        <proportion-progress-bar :value="adForm" mode="ad" title="分佣比例可视化"
                            @change="handleAdProgressBarChange">
                        </proportion-progress-bar>
                    </div>

                    <!-- 商家本店消费分佣配置 -->
                    <div class="commission-config-item">
                        <h4 class="config-item-title">
                            <span>
                                <i class="el-icon-shopping-bag-2"></i>
                                商家本店消费分佣配置
                            </span>
                            <el-button type="primary" size="small" @click="saveMerchantStoreConfig"
                                :loading="merchantStoreLoading">保存配置</el-button>
                        </h4>
                        <p class="config-item-desc">配置各角色在商家本店消费分佣中的分成比例，比例范围为 [0, 100)</p>

                        <!-- 可视化分佣比例展示 -->
                        <proportion-progress-bar :value="merchantStoreForm" mode="alliance" title="分佣比例可视化"
                            @change="handleMerchantStoreProgressBarChange">
                        </proportion-progress-bar>
                    </div>

                    <!-- 异业联盟分佣配置 -->
                    <div class="commission-config-item">
                        <h4 class="config-item-title">
                            <span>
                                <i class="el-icon-connection"></i>
                                异业联盟分佣配置
                            </span>
                            <el-button type="primary" size="small" @click="saveAllianceConfig"
                                :loading="allianceLoading">保存配置</el-button>
                        </h4>
                        <p class="config-item-desc">配置各角色在异业联盟分佣中的分成比例，比例范围为 [0, 100)</p>

                        <!-- 可视化分佣比例展示 -->
                        <proportion-progress-bar :value="allianceForm" mode="alliance-no-salesman" title="分佣比例可视化"
                            @change="handleAllianceProgressBarChange">
                        </proportion-progress-bar>
                    </div>
                </div>
            </div>

        </el-card>

        <!-- 编辑分润比例对话框 -->
        <el-dialog title="编辑分润比例" :visible.sync="editDialogVisible" width="600px" :close-on-click-modal="false"
            custom-class="action-dialog">

            <!-- 用户信息展示卡片 -->
            <div class="user-info-card">
                <div class="info-header">
                    <i class="el-icon-user-solid"></i>
                    <span>用户信息</span>
                </div>
                <div class="info-content">
                    <div class="info-item">
                        <span class="info-label">用户类型：</span>
                        <el-tag :type="getUserTypeTag(editForm.userType)" size="small">
                            {{ editForm.userTypeName }}
                        </el-tag>
                    </div>
                    <div class="info-item">
                        <span class="info-label">用户名称：</span>
                        <span class="info-value">{{ editForm.userName }}</span>
                    </div>
                    <div class="info-item" v-if="editForm.phone">
                        <span class="info-label">手机号码：</span>
                        <span class="info-value">{{ editForm.phone }}</span>
                    </div>
                </div>
            </div>

            <!-- 分润比例配置 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-s-finance"></i>
                    <span>分润比例配置</span>
                </div>

                <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="140px" class="action-form">

                    <!-- 异业联盟分润 -->
                    <el-form-item label="异业联盟分润" prop="interIndustryRate">
                        <div class="input-wrapper">
                            <el-input-number v-model="editForm.interIndustryRate" :min="0" :max="97" :step="1"
                                :precision="0" controls-position="right" style="width: 100%">
                            </el-input-number>
                            <div class="percentage-badge alliance-badge">
                                <i class="el-icon-connection"></i>
                                {{ editForm.interIndustryRate }}%
                            </div>
                        </div>
                        <div class="form-tip">
                            <i class="el-icon-info"></i>
                            异业联盟订单的分润比例，范围：0% - 97%
                        </div>
                    </el-form-item>

                    <!-- 广告分润 -->
                    <el-form-item label="广告分润" prop="adRate">
                        <div class="input-wrapper">
                            <el-input-number v-model="editForm.adRate" :min="0" :max="97" :step="1" :precision="0"
                                controls-position="right" style="width: 100%">
                            </el-input-number>
                            <div class="percentage-badge ad-badge">
                                <i class="el-icon-video-camera"></i>
                                {{ editForm.adRate }}%
                            </div>
                        </div>
                        <div class="form-tip">
                            <i class="el-icon-info"></i>
                            广告收益的分润比例，范围：0% - 97%
                        </div>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 操作按钮 -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false" size="medium">
                    <i class="el-icon-close"></i>
                    取消
                </el-button>
                <el-button type="primary" @click="handleEditSubmit" :loading="editLoading" size="medium">
                    <i class="el-icon-check"></i>
                    确定保存
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserProfitList, editUserProfit, getProportionInfo, editProportion, sendSmsCode } from '@/api/aggregation'
import ProportionProgressBar from '@/components/ProportionProgressBar'

export default {
    name: 'ProportionConfig',
    components: {
        ProportionProgressBar
    },
    data() {
        return {
            loading: false,
            adLoading: false,
            allianceLoading: false,
            merchantStoreLoading: false,
            editLoading: false,
            verifyCode: '',
            smsCountdown: 0,
            smsSending: false,
            smsTimer: null,

            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                keyword: '',  // 搜索关键词：支持姓名模糊搜索、业务员编号精确搜索、手机号精确搜索
                userType: null,  // 用户类型：1=C端，2=业务员，3=商家，4=区域代理
                useCustomConfig: null  // 配置类型：true=自定义，false=默认
            },
            total: 0,

            // 表格列配置
            tableColumns: [
                { prop: 'userTypeName', label: '用户类型', minWidth: 100, align: 'center', slot: 'userTypeName', showOverflowTooltip: true },
                { prop: 'userName', label: '用户名称', minWidth: 100, align: 'center', slot: 'userName', showOverflowTooltip: true },
                { prop: 'phone', label: '手机号码', minWidth: 100, align: 'center', slot: 'phone', showOverflowTooltip: true },
                { prop: 'interIndustryRate', label: '异业联盟分润比例', minWidth: 150, align: 'center', slot: 'interIndustryRate' },
                { prop: 'adRate', label: '广告分润比例', minWidth: 130, align: 'center', slot: 'adRate' },
                { prop: 'lockedSalesmanName', label: '绑定的业务员', minWidth: 130, align: 'center', slot: 'lockedSalesmanName' },
                { prop: 'lockedSalesmanNo', label: '业务员编号', minWidth: 120, align: 'center', slot: 'lockedSalesmanNo' },
                { prop: 'createTime', label: '更新时间', minWidth: 160, align: 'center', showOverflowTooltip: true },
                { prop: 'actions', label: '操作', minWidth: 100, align: 'center', fixed: 'right', slot: 'actions' }
            ],

            // 广告分佣表单
            adForm: {
                company: 35,   // 总公司
                agent: 30,    // 区域代理
                merchant: 20,  // 商家
                user: 15      // 用户
            },

            // 商家本店消费分佣表单
            merchantStoreForm: {
                company: 40,     // 总公司
                agent: 10,       // 区域代理
                salesman: 30,    // 业务员（从商家分佣中获取）
                merchant: 20     // 商家
            },

            // 异业联盟分佣表单（业务员不参与）
            allianceForm: {
                company: 40,     // 总公司
                agent: 30,       // 区域代理
                merchant: 30     // 商家
            },

            // 自动填充标志，防止无限循环
            isAutoFilling: false,
            isAutoFillingAlliance: false,
            isAutoFillingAd: false,

            // 分润比例列表
            proportionList: [],
            proportionIdMap: {},

            // 编辑对话框
            editDialogVisible: false,
            editForm: {},
            editRules: {
                proportion: [
                    { required: true, message: '请输入分成比例', trigger: 'blur' },
                    { type: 'number', min: 0, max: 97, message: '比例必须在 [0, 100) 范围内', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        ...mapGetters(['userPhone']),
        // 广告分佣总和百分比
        adTotalPercentage() {
            const total = this.adForm.company + this.adForm.agent + this.adForm.merchant + this.adForm.user
            return total
        },
        // 商家本店消费分佣总和百分比（业务员分佣从商家分佣中获取，不参与总分计算）
        merchantStoreTotalPercentage() {
            // 业务员分佣是从商家分佣中获得的，所以总分佣只计算：公司 + 区域代理 + 商家
            const total = this.merchantStoreForm.company + this.merchantStoreForm.agent + this.merchantStoreForm.merchant
            return total
        },
        // 异业联盟分佣总和百分比（业务员不参与）
        allianceTotalPercentage() {
            // 异业联盟分佣：公司 + 区域代理 + 商家
            const total = this.allianceForm.company + this.allianceForm.agent + this.allianceForm.merchant
            return total
        },
        // 业务员实际分佣比例（相对于总订单金额，仅商家本店消费）
        salesmanActualRate() {
            // 业务员实际分佣 = 商家分佣比例 × 业务员分佣比例
            return (this.merchantStoreForm.merchant * this.merchantStoreForm.salesman / 100).toFixed(2)
        }
    },
    watch: {
        // 监听商家本店消费分佣总和，确保为100%
        merchantStoreTotalPercentage(newVal) {
            // 如果总和不为100%，自动规范化
            if (Math.abs(newVal - 100) > 0.01 && !this.isAutoFilling) {
                this.isAutoFilling = true
                this.normalizeFormTo100(this.merchantStoreForm, 'alliance')
                // 使用 nextTick 确保更新完成后再重置标志
                this.$nextTick(() => {
                    this.isAutoFilling = false
                })
            }
        },
        // 监听异业联盟分佣总和，确保为100%
        allianceTotalPercentage(newVal) {
            // 如果总和不为100%，自动规范化
            if (Math.abs(newVal - 100) > 0.01 && !this.isAutoFillingAlliance) {
                this.isAutoFillingAlliance = true
                this.normalizeFormTo100(this.allianceForm, 'alliance-no-salesman')
                // 使用 nextTick 确保更新完成后再重置标志
                this.$nextTick(() => {
                    this.isAutoFillingAlliance = false
                })
            }
        },
        // 监听广告分佣总和，确保为100%
        adTotalPercentage(newVal) {
            // 如果总和不为100%，自动规范化
            if (Math.abs(newVal - 100) > 0.01 && !this.isAutoFillingAd) {
                this.isAutoFillingAd = true
                this.normalizeFormTo100(this.adForm, 'ad')
                // 使用 nextTick 确保更新完成后再重置标志
                this.$nextTick(() => {
                    this.isAutoFillingAd = false
                })
            }
        }
    },
    mounted() {
        this.loadUserProfitList()
        this.loadProportionConfig()
    },
    beforeDestroy() {
        // 清理拖动事件监听器
        this.clearSmsTimer()
        this.endDrag()
        document.removeEventListener('mousemove', this.handleDocumentMouseMove)
        document.removeEventListener('mouseup', this.handleDocumentMouseUp)
    },
    methods: {
        // 刷新所有数据
        async refreshAllData() {
            await Promise.all([
                this.loadUserProfitList(),
                this.loadProportionConfig()
            ])
        },

        // 加载分润比例列表（用于表格显示）
        async loadUserProfitList() {
            this.loading = true
            try {
                // 构建请求参数
                const params = {
                    pageIndex: this.queryParams.pageIndex,
                    pageSize: this.queryParams.pageSize
                }

                // 添加查询条件（只有在有值的情况下才添加）
                if (this.queryParams.userType !== null && this.queryParams.userType !== undefined && this.queryParams.userType !== '') {
                    params.userType = this.queryParams.userType
                }
                if (this.queryParams.useCustomConfig !== null && this.queryParams.useCustomConfig !== undefined && this.queryParams.useCustomConfig !== '') {
                    params.useCustomConfig = this.queryParams.useCustomConfig
                }

                Logger.log('加载分润比例列表，参数:', params)
                const response = await getUserProfitList(params)
                Logger.log('分润比例列表API响应:', response)

                if (response.code === 0) {
                    // 处理分页数据
                    if (response.data && response.data.list) {
                        // 分页格式
                        this.proportionList = response.data.list || []
                        this.total = response.data.total || 0
                    } else if (Array.isArray(response.data)) {
                        // 列表格式
                        this.proportionList = response.data
                        this.total = response.data.length
                    } else {
                        this.proportionList = []
                        this.total = 0
                    }
                } else {
                    this.$message.error(response.msg || '加载分润比例列表失败')
                }
            } catch (error) {
                Logger.error('加载分润比例列表失败:', error)
                this.$message.error('加载分润比例列表失败')
            } finally {
                this.loading = false
            }
        },

        // 加载分佣比例配置信息（用于广告分佣和异业联盟配置）
        async loadProportionConfig() {
            try {
                Logger.log('加载分佣配置信息')
                const response = await getProportionInfo()
                Logger.log('分佣配置信息API响应:', response)

                if (response.code === 0) {
                    this.initFormData(response.data || [])
                } else {
                    this.$message.error('加载分佣配置信息失败')
                }
            } catch (error) {
                Logger.error('加载分佣配置信息失败:', error)
                this.$message.error('加载分佣配置信息失败')
            }
        },

        // 规范化表单数据总和为100%
        normalizeFormTo100(form, mode = 'ad') {
            if (mode === 'ad') {
                const total = form.company + form.agent + form.merchant + form.user
                if (total > 0 && Math.abs(total - 100) > 0.01) {
                    const ratio = 100 / total
                    form.company = Math.max(1, Math.round(form.company * ratio))
                    form.agent = Math.max(1, Math.round(form.agent * ratio))
                    form.merchant = Math.max(1, Math.round(form.merchant * ratio))
                    form.user = Math.max(1, Math.round(form.user * ratio))

                    // 微调确保总和为100%
                    const newTotal = form.company + form.agent + form.merchant + form.user
                    const diff = 100 - newTotal
                    if (diff !== 0) {
                        if (form.company >= form.agent && form.company >= form.merchant && form.company >= form.user) {
                            form.company += diff
                        } else if (form.agent >= form.merchant && form.agent >= form.user) {
                            form.agent += diff
                        } else if (form.merchant >= form.user) {
                            form.merchant += diff
                        } else {
                            form.user += diff
                        }
                    }
                }
            } else {
                // alliance 或 alliance-no-salesman 模式
                const total = form.company + form.agent + form.merchant
                if (total > 0 && Math.abs(total - 100) > 0.01) {
                    const ratio = 100 / total
                    form.company = Math.max(1, Math.round(form.company * ratio))
                    form.agent = Math.max(1, Math.round(form.agent * ratio))
                    form.merchant = Math.max(1, Math.round(form.merchant * ratio))

                    // 微调确保总和为100%
                    const newTotal = form.company + form.agent + form.merchant
                    const diff = 100 - newTotal
                    if (diff !== 0) {
                        if (form.company >= form.agent && form.company >= form.merchant) {
                            form.company += diff
                        } else if (form.agent >= form.merchant) {
                            form.agent += diff
                        } else {
                            form.merchant += diff
                        }
                    }
                }
            }
        },

        getProportionKey(type, roleType) {
            return `${type}-${roleType}`
        },

        getProportionId(type, roleType) {
            const key = this.getProportionKey(type, roleType)
            return this.proportionIdMap[key]
        },

        cacheProportionId(item) {
            if (!item || item.type === undefined || item.roleType === undefined || !item.id) {
                return
            }
            const key = this.getProportionKey(item.type, item.roleType)
            this.$set(this.proportionIdMap, key, item.id)
        },

        createConfigItem(type, roleType, proportion) {
            const config = {
                type,
                roleType,
                proportion: Number(proportion)
            }
            const id = this.getProportionId(type, roleType)
            if (id) {
                config.id = id
            }
            return config
        },

        buildBatchEditPayload(configs) {
            const code = (this.verifyCode || '').trim()
            if (!code) {
                this.$message.warning('请先输入短信验证码')
                return null
            }
            if (!Array.isArray(configs) || !configs.length) {
                this.$message.error('缺少分佣配置数据')
                return null
            }
            return {
                verifyCode: code,
                proportions: configs
            }
        },

        // 初始化表单数据
        initFormData(configData) {
            // 重置表单数据，设置默认最小值为1%
            this.adForm = { company: 1, agent: 1, merchant: 1, user: 1 }
            this.merchantStoreForm = { company: 1, agent: 1, salesman: 30, merchant: 1 }
            this.allianceForm = { company: 1, agent: 1, merchant: 1 }
            this.proportionIdMap = {}

            // 根据API数据填充表单，确保最小值不小于1%
            configData.forEach(item => {
                this.cacheProportionId(item)
                const proportion = Math.max(1, item.proportion || 1) // 确保不小于1%
                if (item.type === 1) { // 广告分佣
                    switch (item.roleType) {
                        case 1: this.adForm.user = proportion; break;    // 用户
                        case 3: this.adForm.merchant = proportion; break; // 商家
                        case 4: this.adForm.agent = proportion; break;   // 区域代理
                        case 5: this.adForm.company = proportion; break; // 总公司
                    }
                } else if (item.type === 2) { // 异业联盟分佣（业务员不参与）
                    switch (item.roleType) {
                        case 3: this.allianceForm.merchant = proportion; break; // 商家
                        case 4: this.allianceForm.agent = proportion; break;    // 区域代理
                        case 5: this.allianceForm.company = proportion; break;  // 总公司
                    }
                } else if (item.type === 3) { // 商家本店消费分佣
                    switch (item.roleType) {
                        case 2: this.merchantStoreForm.salesman = Math.max(1, Math.min(99, proportion)); break; // 业务员（1-99%）
                        case 3: this.merchantStoreForm.merchant = proportion; break; // 商家
                        case 4: this.merchantStoreForm.agent = proportion; break;    // 区域代理
                        case 5: this.merchantStoreForm.company = proportion; break;  // 总公司
                    }
                }
            })

            // 确保所有表单总和为100%
            this.normalizeFormTo100(this.adForm, 'ad')
            this.normalizeFormTo100(this.merchantStoreForm, 'alliance')
            this.normalizeFormTo100(this.allianceForm, 'alliance-no-salesman')
        },

        async handleSendVerifyCode() {
            if (!this.userPhone) {
                this.$message.error('当前账号未绑定手机号，无法发送验证码')
                return
            }
            if (this.smsCountdown > 0 || this.smsSending) {
                return
            }
            this.smsSending = true
            try {
                const response = await sendSmsCode({ phone: this.userPhone })
                if (!response || response.code === 0) {
                    this.$message.success('验证码已发送，请注意查收短信')
                    this.startSmsCountdown()
                } else {
                    this.$message.error(response.msg || '验证码发送失败')
                }
            } catch (error) {
                Logger.error('发送短信验证码失败:', error)
                this.$message.error('验证码发送失败，请稍后重试')
            } finally {
                this.smsSending = false
            }
        },

        startSmsCountdown() {
            this.smsCountdown = 60
            this.clearSmsTimer()
            this.smsTimer = setInterval(() => {
                if (this.smsCountdown <= 1) {
                    this.clearSmsTimer()
                    this.smsCountdown = 0
                } else {
                    this.smsCountdown -= 1
                }
            }, 1000)
        },

        clearSmsTimer() {
            if (this.smsTimer) {
                clearInterval(this.smsTimer)
                this.smsTimer = null
            }
        },

        maskPhone(phone) {
            if (!phone) {
                return ''
            }
            // 确保 phone 是字符串类型
            const phoneStr = String(phone)
            return phoneStr.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        },

        // 查询按钮
        handleQuery() {
            this.queryParams.pageIndex = 1
            this.loadUserProfitList()
        },

        // 重置按钮
        handleReset() {
            this.queryParams = {
                pageIndex: 1,
                pageSize: 10,
                keyword: '',
                userType: null,
                useCustomConfig: null
            }
            this.loadUserProfitList()
        },

        // 分页改变事件（统一处理）
        handlePageChange({ currentPage, pageSize }) {
            this.queryParams.pageIndex = currentPage
            this.queryParams.pageSize = pageSize
            this.loadUserProfitList()
        },

        // 每页条数改变（保留以兼容旧代码，实际使用 handlePageChange）
        handleSizeChange(val) {
            this.queryParams.pageSize = val
            this.queryParams.pageIndex = 1
            this.loadUserProfitList()
        },

        // 当前页改变（保留以兼容旧代码，实际使用 handlePageChange）
        handleCurrentChange(val) {
            this.queryParams.pageIndex = val
            this.loadUserProfitList()
        },

        // 保存广告分佣配置
        async saveAdConfig() {
            // 验证每个比例不能小于1%
            if (this.adForm.company < 1 || this.adForm.agent < 1 || this.adForm.merchant < 1 || this.adForm.user < 1) {
                this.$message.warning('每个分佣比例不能小于1%，请调整后再保存')
                return
            }

            this.adLoading = true
            try {
                await this.saveConfigs('广告分佣')
            } catch (error) {
                Logger.error('保存广告分佣配置失败:', error)
                this.$message.error('保存广告分佣配置失败')
            } finally {
                this.adLoading = false
            }
        },

        // 保存商家本店消费分佣配置
        async saveMerchantStoreConfig() {
            // 验证每个比例不能小于1%
            if (this.merchantStoreForm.company < 1 || this.merchantStoreForm.agent < 1 || this.merchantStoreForm.merchant < 1 || this.merchantStoreForm.salesman < 1) {
                this.$message.warning('每个分佣比例不能小于1%，请调整后再保存')
                return
            }

            this.merchantStoreLoading = true
            try {
                await this.saveMerchantStoreConfigs('商家本店消费分佣')
            } catch (error) {
                Logger.error('保存商家本店消费分佣配置失败:', error)
                this.$message.error('保存商家本店消费分佣配置失败')
            } finally {
                this.merchantStoreLoading = false
            }
        },

        // 保存异业联盟分佣配置
        async saveAllianceConfig() {
            // 验证每个比例不能小于1%
            if (this.allianceForm.company < 1 || this.allianceForm.agent < 1 || this.allianceForm.merchant < 1) {
                this.$message.warning('每个分佣比例不能小于1%，请调整后再保存')
                return
            }

            this.allianceLoading = true
            try {
                await this.saveAllianceConfigs('异业联盟分佣')
            } catch (error) {
                Logger.error('保存异业联盟分佣配置失败:', error)
                this.$message.error('保存异业联盟分佣配置失败')
            } finally {
                this.allianceLoading = false
            }
        },

        // 保存广告分佣配置
        async saveConfigs(typeName) {
            const configs = [
                this.createConfigItem(1, 5, this.adForm.company), // 广告 总公司
                this.createConfigItem(1, 4, this.adForm.agent),   // 广告 区域代理
                this.createConfigItem(1, 3, this.adForm.merchant), // 广告 商家
                this.createConfigItem(1, 1, this.adForm.user)     // 广告 用户
            ]
            const payload = this.buildBatchEditPayload(configs)
            if (!payload) {
                return
            }
            // 仅调用修改接口
            const response = await editProportion(payload)
            if (response.code === 0) {
                this.$message.success(`${typeName}配置保存成功`)
                this.verifyCode = ''
                this.refreshAllData() // 重新加载数据
            } else {
                this.$message.error(`${typeName}配置保存失败: ${response.msg}`)
            }
        },

        // 保存商家本店消费分佣配置
        async saveMerchantStoreConfigs(typeName) {
            const configs = [
                this.createConfigItem(3, 5, this.merchantStoreForm.company),  // 商家本店消费 总公司
                this.createConfigItem(3, 4, this.merchantStoreForm.agent),    // 商家本店消费 区域代理
                this.createConfigItem(3, 3, this.merchantStoreForm.merchant),  // 商家本店消费 商家
                this.createConfigItem(3, 2, this.merchantStoreForm.salesman)   // 商家本店消费 业务员
            ]
            const payload = this.buildBatchEditPayload(configs)
            if (!payload) {
                return
            }
            // 仅调用修改接口
            const response = await editProportion(payload)
            if (response.code === 0) {
                this.$message.success(`${typeName}配置保存成功`)
                this.verifyCode = ''
                this.refreshAllData() // 重新加载数据
            } else {
                this.$message.error(`${typeName}配置保存失败: ${response.msg}`)
            }
        },

        // 保存异业联盟分佣配置
        async saveAllianceConfigs(typeName) {
            const configs = [
                this.createConfigItem(2, 5, this.allianceForm.company),  // 异业联盟 总公司
                this.createConfigItem(2, 4, this.allianceForm.agent),    // 异业联盟 区域代理
                this.createConfigItem(2, 3, this.allianceForm.merchant)  // 异业联盟 商家
            ]
            const payload = this.buildBatchEditPayload(configs)
            if (!payload) {
                return
            }
            // 仅调用修改接口
            const response = await editProportion(payload)
            if (response.code === 0) {
                this.$message.success(`${typeName}配置保存成功`)
                this.verifyCode = ''
                this.refreshAllData() // 重新加载数据
            } else {
                this.$message.error(`${typeName}配置保存失败: ${response.msg}`)
            }
        },

        // 编辑分润比例
        editUserProfitFunc(row) {
            this.editForm = { ...row }
            Logger.log('编辑分润比例，参数:', this.editForm)
            this.editDialogVisible = true
        },

        // 提交编辑
        async handleEditSubmit() {
            try {
                await this.$refs.editForm.validate()
                this.editLoading = true
                if (this.editForm.userType === 3) {
                    this.editForm.interIndustryMerchantRate = this.editForm.interIndustryRate;
                    this.editForm.adMerchantRate = this.editForm.adRate;
                }

                Logger.log('编辑分润比例，参数:', this.editForm)
                const response = await editUserProfit(this.editForm)
                Logger.log('编辑分润比例API响应:', response)

                if (response.code === 0) {
                    this.$message.success('编辑成功')
                    this.editDialogVisible = false
                    this.refreshAllData() // 重新加载数据
                } else {
                    this.$message.error('编辑失败: ' + (response.data?.msg || '未知错误'))
                }
            } catch (error) {
                Logger.error('编辑分润比例失败:', error)
                this.$message.error('编辑失败，请重试')
            } finally {
                this.editLoading = false
            }
        },

        // 获取分佣类型标签
        getTypeTag(type) {
            const typeMap = {
                1: 'primary',  // 广告分佣
                2: 'success',  // 异业联盟分佣
                3: 'warning'   // 商家固定抽成
            }
            return typeMap[type] || 'info'
        },

        // 获取用户类型标签样式
        getUserTypeTag(userType) {
            const tagMap = {
                1: 'info',     // C端用户
                2: 'warning',  // 业务员
                3: 'success',  // 商家
                4: 'primary'   // 区域代理
            }
            return tagMap[userType] || 'info'
        },

        // 获取分佣类型文本
        getTypeText(type) {
            const typeMap = {
                1: '广告分佣',
                2: '异业联盟分佣',
                3: '商家固定抽成'
            }
            return typeMap[type] || '未知类型'
        },

        // 获取角色标签
        getRoleTag(roleType) {
            const roleMap = {
                1: 'info',     // 用户
                2: 'warning',  // 业务员
                3: 'success',  // 商家
                4: 'primary',  // 区域代理
                5: 'danger'    // 总公司
            }
            return roleMap[roleType] || 'info'
        },

        // 获取角色文本
        getRoleText(roleType) {
            const roleMap = {
                1: '用户',
                2: '业务员',
                3: '商家',
                4: '区域代理',
                5: '总公司'
            }
            return roleMap[roleType] || '未知角色'
        },

        // 处理商家本店消费进度条拖动完成事件
        handleMerchantStoreProgressBarChange(values) {
            // 更新表单值
            this.merchantStoreForm.company = values.company
            this.merchantStoreForm.agent = values.agent
            this.merchantStoreForm.merchant = values.merchant
            this.merchantStoreForm.salesman = values.salesman

            // 触发自动补充检查（如果需要）
            this.$nextTick(() => {
                if (values.total < 100) {
                    // 触发自动补充（通过重新计算来触发watch）
                    const temp = this.merchantStoreForm.merchant
                    this.merchantStoreForm.merchant = temp
                }
            })
        },

        // 处理异业联盟进度条拖动完成事件
        handleAllianceProgressBarChange(values) {
            // 更新表单值
            this.allianceForm.company = values.company
            this.allianceForm.agent = values.agent
            this.allianceForm.merchant = values.merchant

            // 触发自动补充检查（如果需要）
            this.$nextTick(() => {
                if (values.total < 100) {
                    // 触发自动补充（通过重新计算来触发watch）
                    const temp = this.allianceForm.merchant
                    this.allianceForm.merchant = temp
                }
            })
        },

        // 处理广告分佣进度条拖动完成事件
        handleAdProgressBarChange(values) {
            // 更新表单值
            this.adForm.company = values.company
            this.adForm.agent = values.agent
            this.adForm.merchant = values.merchant
            this.adForm.user = values.user
        },

        // 获取广告分佣卡片数据
        getAdProportionItems() {
            return [
                {
                    key: 'company',
                    label: '总公司',
                    value: this.adForm.company || 0,
                    icon: 'el-icon-office-building',
                    color: '#409eff'
                },
                {
                    key: 'agent',
                    label: '区域代理',
                    value: this.adForm.agent || 0,
                    icon: 'el-icon-user',
                    color: '#67c23a'
                },
                {
                    key: 'merchant',
                    label: '商家',
                    value: this.adForm.merchant || 0,
                    icon: 'el-icon-s-shop',
                    color: '#e6a23c'
                },
                {
                    key: 'user',
                    label: '用户',
                    value: this.adForm.user || 0,
                    icon: 'el-icon-user-solid',
                    color: '#f56c6c'
                }
            ]
        },

        // 获取广告分佣总和
        getAdTotal() {
            const total = this.adForm.company + this.adForm.agent + this.adForm.merchant + this.adForm.user
            return parseFloat(total.toFixed(2))
        },

        // 获取商家本店消费分佣卡片数据
        getMerchantStoreProportionItems() {
            const salesmanActual = (this.merchantStoreForm.merchant * this.merchantStoreForm.salesman / 100).toFixed(2)
            return [
                {
                    key: 'company',
                    label: '总公司',
                    value: this.merchantStoreForm.company || 0,
                    icon: 'el-icon-office-building',
                    color: '#409eff'
                },
                {
                    key: 'agent',
                    label: '区域代理',
                    value: this.merchantStoreForm.agent || 0,
                    icon: 'el-icon-user',
                    color: '#67c23a'
                },
                {
                    key: 'merchant',
                    label: '商家',
                    value: this.merchantStoreForm.merchant || 0,
                    icon: 'el-icon-s-shop',
                    color: '#e6a23c',
                    subtitle: `其中业务员：${salesmanActual}%`
                }
            ]
        },

        // 获取商家本店消费分佣总和
        getMerchantStoreTotal() {
            const total = this.merchantStoreForm.company + this.merchantStoreForm.agent + this.merchantStoreForm.merchant
            return parseFloat(total.toFixed(2))
        },

        // 获取异业联盟分佣卡片数据
        getAllianceProportionItems() {
            return [
                {
                    key: 'company',
                    label: '总公司',
                    value: this.allianceForm.company || 0,
                    icon: 'el-icon-office-building',
                    color: '#409eff'
                },
                {
                    key: 'agent',
                    label: '区域代理',
                    value: this.allianceForm.agent || 0,
                    icon: 'el-icon-user',
                    color: '#67c23a'
                },
                {
                    key: 'merchant',
                    label: '商家',
                    value: this.allianceForm.merchant || 0,
                    icon: 'el-icon-s-shop',
                    color: '#e6a23c'
                }
            ]
        },

        // 获取异业联盟分佣总和
        getAllianceTotal() {
            const total = this.allianceForm.company + this.allianceForm.agent + this.allianceForm.merchant
            return parseFloat(total.toFixed(2))
        },
    }
}
</script>

<style scoped>
.proportion-config {
    padding: 20px;
}

.config-section {
    margin-bottom: 40px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
}

.section-title {
    color: #2c3e50;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

/* 分佣配置模块样式 */
.commission-config-section {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
}

.verify-section {
    margin-bottom: 20px;
}

.verify-form {
    margin-top: 12px;
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}

.verify-input {
    width: 320px;
    max-width: 100%;
}

.verify-help {
    font-size: 13px;
    color: #909399;
}

.verify-help.danger {
    color: #f56c6c;
}

/* 分佣比例概览模块样式 */
.commission-overview-section {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
}

/* 分佣配置容器 - 横向排列 */
.commission-config-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-top: 20px;
}

/* 分佣比例概览容器 - 横向排列 */
.commission-overview-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-top: 20px;
}

.commission-config-item {
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    min-height: 100%;
}

.commission-config-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border-color: #409eff;
}

.commission-overview-item {
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    min-height: 100%;
}

.commission-overview-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border-color: #409eff;
}

.config-item-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
    flex-wrap: wrap;
    gap: 8px;
}

.config-item-title span {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    flex: 1;
    min-width: 0;
}

.config-item-title i {
    margin-right: 8px;
    font-size: 18px;
    color: #409eff;
}

.overview-item-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
    flex-wrap: wrap;
    gap: 8px;
}

.overview-item-title span {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    flex: 1;
    min-width: 0;
}

.overview-item-title i {
    margin-right: 8px;
    font-size: 18px;
    color: #409eff;
}

.config-item-desc {
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 20px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 6px;
    border-left: 3px solid #409eff;
    overflow-wrap: break-word;
    word-break: break-word;
}

.overview-item-desc {
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 20px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 6px;
    border-left: 3px solid #409eff;
    overflow-wrap: break-word;
    word-break: break-word;
}

.proportion-progress-bar {
    flex: 1;
}

/* 卡片式比例展示样式 */
.proportion-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 16px;
    margin-top: 20px;
}

.proportion-card {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    border: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    overflow: hidden;
}

.proportion-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #409eff, #67c23a);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.proportion-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    border-color: #409eff;
}

.proportion-card:hover::before {
    opacity: 1;
}

.proportion-card.total-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: 2px solid #e4e7ed;
    font-weight: 600;
}

.proportion-card.total-card:hover {
    border-color: #67c23a;
}

.card-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 12px;
    color: #fff;
    font-size: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.card-icon.icon-success {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.card-icon.icon-warning {
    background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.card-content {
    text-align: center;
    width: 100%;
}

.card-label {
    font-size: 13px;
    color: #606266;
    margin-bottom: 8px;
    font-weight: 500;
}

.proportion-card.total-card .card-label {
    color: #303133;
    font-size: 14px;
}

.card-value {
    font-size: 24px;
    font-weight: 700;
    color: #303133;
    margin-bottom: 8px;
    line-height: 1.2;
}

.card-value.text-success {
    color: #67c23a;
}

.card-value.text-danger {
    color: #f56c6c;
}

.card-subtitle {
    font-size: 11px;
    color: #909399;
    margin-top: 4px;
    font-style: italic;
}

.card-progress {
    width: 100%;
    height: 4px;
    background: #f0f2f5;
    border-radius: 2px;
    overflow: hidden;
    margin-top: 8px;
}

.proportion-card.total-card .card-progress {
    display: none;
}

.progress-bar {
    height: 100%;
    border-radius: 2px;
    transition: width 0.3s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.section-title span {
    display: flex;
    align-items: center;
}

.section-title i {
    margin-right: 8px;
    font-size: 20px;
}

.section-desc {
    color: #6c757d;
    font-size: 14px;
    margin-bottom: 20px;
    line-height: 1.5;
}

.query-form {
    background: white;
    padding: 15px 20px 0;
    border-radius: 6px;
    margin-bottom: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.config-form {
    background: white;
    padding: 20px;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.proportion-text {
    margin-left: 10px;
    color: #409eff;
    font-weight: 600;
    font-size: 14px;
}

.form-tip {
    display: flex;
    align-items: center;
    margin-top: 8px;
    padding: 8px 12px;
    background: #f0f9ff;
    border-left: 3px solid #409eff;
    border-radius: 4px;
    font-size: 12px;
    color: #606266;
}

.form-tip i {
    margin-right: 6px;
    color: #409eff;
    font-size: 14px;
}

.proportion-display {
    color: #409eff;
    font-weight: 600;
    font-size: 16px;
}

/* 表格样式优化 */
.el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-table th {
    background: #fafafa;
    color: #303133;
    font-weight: 600;
    padding: 12px 0;
}

.el-table td {
    padding: 12px 0;
}

.el-table .cell {
    padding: 0 12px;
}

/* 页面标题样式 */
.page-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

/* 卡片头部样式 */
.el-card__header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-bottom: 1px solid #dee2e6;
    border-radius: 8px 8px 0 0;
    padding: 20px 24px;
}

.el-card__header .clearfix {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-card__header .page-title {
    color: #2c3e50;
    font-size: 22px;
    font-weight: 700;
    letter-spacing: 0.5px;
}

/* 分佣比例卡片样式 */
.commission-cards {
    margin-top: 20px;
}

.card-group {
    margin-bottom: 30px;
}

.card-group-title {
    color: #2c3e50;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 2px solid #e9ecef;
}

.card-group-title i {
    margin-right: 8px;
    font-size: 18px;
    color: #409eff;
}

.cards-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.commission-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.commission-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #409eff, #67c23a);
}

.commission-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
}

.card-header .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    display: flex;
    align-items: center;
}

.card-icon {
    margin-right: 8px;
    font-size: 18px;
}

.card-content {
    text-align: center;
}

.proportion-value {
    font-size: 32px;
    font-weight: 700;
    color: #409eff;
    margin-bottom: 8px;
    text-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.proportion-desc {
    color: #6c757d;
    font-size: 14px;
    line-height: 1.4;
}

/* 商家卡片特殊样式 */
.merchant-card {
    border-left: 4px solid #67c23a;
    background: linear-gradient(135deg, #f0f9ff 0%, #e6fffa 100%);
}

.merchant-card::before {
    background: linear-gradient(90deg, #67c23a, #85ce61);
}

.merchant-card .proportion-value {
    color: #67c23a;
}

/* 用户卡片样式 */
.user-card {
    border-left: 4px solid #909399;
}

.user-card::before {
    background: linear-gradient(90deg, #909399, #b1b3b8);
}

.user-card .proportion-value {
    color: #909399;
}

/* 区域代理卡片样式 */
.agent-card {
    border-left: 4px solid #409eff;
}

.agent-card::before {
    background: linear-gradient(90deg, #409eff, #66b1ff);
}

.agent-card .proportion-value {
    color: #409eff;
}

/* 业务员卡片样式 */
.salesman-card {
    border-left: 4px solid #e6a23c;
    background: linear-gradient(135deg, #fef9e7 0%, #fdf6ec 100%);
}

.salesman-card::before {
    background: linear-gradient(90deg, #e6a23c, #ebb563);
}

.salesman-card .proportion-value {
    color: #e6a23c;
}

/* 总公司卡片样式 */
.company-card {
    border-left: 4px solid #f56c6c;
    background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%);
}

.company-card::before {
    background: linear-gradient(90deg, #f56c6c, #f78989);
}

.company-card .proportion-value {
    color: #f56c6c;
}

/* 分佣比例可视化样式 */
.proportion-visualization {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    overflow: visible;
}

.visual-title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.visual-title i {
    margin-right: 8px;
    font-size: 18px;
    color: #409eff;
}

.outer-progress-container {
    width: 100%;
    overflow: visible;
}

.progress-labels {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    flex-wrap: wrap;
    gap: 8px;
}

.progress-label {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
}

.progress-total {
    font-size: 14px;
    font-weight: 600;
    padding: 4px 12px;
    border-radius: 4px;
    background: #f0f2f5;
}

.progress-total.text-success {
    color: #67c23a;
    background: #f0f9ff;
}

.progress-total.text-danger {
    color: #f56c6c;
    background: #fef0f0;
}

.outer-progress-bar {
    display: flex;
    width: 100%;
    height: 48px;
    background: #f0f2f5;
    border-radius: 8px;
    overflow: visible;
    border: 2px solid #e4e7ed;
    position: relative;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
}

.outer-progress-container {
    overflow: visible;
}

.progress-segment {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    transition: all 0.3s ease;
    min-width: 0;
    border-right: 1px solid rgba(255, 255, 255, 0.3);
    overflow: visible;
}

.progress-segment:last-child {
    border-right: none;
}

.company-segment {
    background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
}

.agent-segment {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.merchant-segment {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    position: relative;
}

.segment-label {
    color: #ffffff;
    font-size: 14px;
    font-weight: 600;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
    white-space: nowrap;
    z-index: 10;
}

/* 嵌套进度条（商家内部） */
.inner-progress-bar {
    position: absolute;
    top: 2px;
    left: 2px;
    right: 2px;
    bottom: 2px;
    display: flex;
    border-radius: 4px;
    overflow: visible;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.inner-segment {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    transition: all 0.3s ease;
}

.merchant-remain-segment {
    background: rgba(103, 194, 58, 0.85);
}

.salesman-segment {
    background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
    border-left: 1px solid rgba(255, 255, 255, 0.3);
}

.inner-label {
    color: #ffffff;
    font-size: 11px;
    font-weight: 600;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
    white-space: nowrap;
    z-index: 10;
}

/* 拖动手柄样式 */
.drag-handle {
    position: absolute;
    top: -4px;
    bottom: -4px;
    width: 8px;
    margin-left: -4px;
    z-index: 100;
    cursor: col-resize;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.drag-handle:hover {
    width: 12px;
    margin-left: -6px;
}

.drag-handle:hover .drag-handle-bar {
    width: 100%;
    background: #409eff;
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.6);
}

.drag-handle-bar {
    width: 4px;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    border: 2px solid #409eff;
    border-radius: 2px;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
}

.outer-drag-handle {
    top: -6px;
    bottom: -6px;
}

.outer-drag-handle .drag-handle-bar {
    background: rgba(255, 255, 255, 0.95);
    border: 2px solid #409eff;
    box-shadow: 0 0 6px rgba(64, 158, 255, 0.5);
}

.inner-drag-handle {
    top: -2px;
    bottom: -2px;
}

.inner-drag-handle .drag-handle-bar {
    background: rgba(255, 255, 255, 0.9);
    border: 1.5px solid #e6a23c;
    box-shadow: 0 0 4px rgba(230, 162, 60, 0.5);
}

.inner-drag-handle:hover .drag-handle-bar {
    background: #e6a23c;
    box-shadow: 0 0 8px rgba(230, 162, 60, 0.6);
}

/* 商家内部说明 */
.merchant-detail {
    margin-top: 16px;
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 3px solid #67c23a;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.detail-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.detail-color {
    width: 16px;
    height: 16px;
    border-radius: 3px;
    flex-shrink: 0;
}

.merchant-remain-color {
    background: #67c23a;
}

.salesman-color {
    background: #e6a23c;
}

.detail-text {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {

    .commission-config-container,
    .commission-overview-container {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .config-form .el-col {
        margin-bottom: 15px;
    }

    .commission-config-container,
    .commission-overview-container {
        grid-template-columns: 1fr;
        gap: 15px;
    }

    .commission-config-section,
    .commission-overview-section {
        padding: 16px;
    }

    .commission-config-item,
    .commission-overview-item {
        padding: 16px;
    }

    .cards-container {
        grid-template-columns: 1fr;
        gap: 15px;
    }

    .commission-card {
        padding: 15px;
    }

    .proportion-value {
        font-size: 28px;
    }

    .proportion-visualization {
        padding: 16px;
    }

    .outer-progress-bar {
        height: 40px;
    }

    .progress-labels {
        flex-direction: column;
        align-items: flex-start;
        gap: 6px;
    }

    .merchant-detail {
        flex-direction: column;
        gap: 12px;
    }

    .proportion-cards {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }

    .proportion-card {
        padding: 12px;
    }

    .card-icon {
        width: 40px;
        height: 40px;
        font-size: 20px;
    }

    .card-value {
        font-size: 20px;
    }
}

@media (max-width: 480px) {
    .proportion-value {
        font-size: 24px;
    }

    .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .proportion-cards {
        grid-template-columns: 1fr;
        gap: 10px;
    }

    .proportion-card {
        padding: 14px;
    }

    .card-icon {
        width: 36px;
        height: 36px;
        font-size: 18px;
    }

    .card-value {
        font-size: 18px;
    }

    .card-label {
        font-size: 12px;
    }
}
</style>
